class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  require 'humble_openid'
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_filter :set_locale

  include OpenidSystem::OpenidServerSystem
  include OpenidSystem::OpenidAuthenticatedSystem

  rescue_from ::ActiveRecord::RecordNotFound, :with => :render_404
  rescue_from ::ActionController::InvalidAuthenticityToken, :with => :render_422

  helper_method :extract_host, :extract_login_from_identifier, :checkid_request,
      :identifier, :endpoint_url, :scheme, :email_as_login?

  #
  #
  #
  #after server sign in
  def after_sign_in_path_for(resource)
    # dashboard_console_path
    if return_to = session[:return_to]
      session[:return_to] = nil
    return_to
    else
      identifier(resource)
    end
  end

  #
  #
  #
  #after server sign up
  def after_sign_up_path_for(resource)
    # dashboard_console_path
    new_user_session_path
  end
  
  def logged_in?
    user_signed_in?
  end

  def set_locale
    I18n.locale = I18n.default_locale  || params[:locale]
  end
  
  def site_conf(key)
    @conf ||= YAML.load_file("#{Rails.root}/config/realtime_update_role.yml")
    @conf[key]
  end
  
  protected

  def endpoint_url
    server_url(:protocol => scheme)
  end

  # Returns the OpenID identifier for an user
  def identifier(user)
    identity_url(:user => user.username, :protocol => scheme)
  end

  # Extracts the hostname from the given url, which is used to
  # display the name of the requesting website to the user
  def extract_host(u)
    URI.split(u).compact[1]
  end

  def extract_login_from_identifier(openid_url)
    openid_url.gsub(/^https?:\/\/.*\//, '')
  end

  def checkid_request
    unless @checkid_request
      req = openid_server.decode_request(current_openid_request.parameters) if current_openid_request
      @checkid_request = req.is_a?(OpenID::Server::CheckIDRequest) ? req : false
    end
    @checkid_request
  end

  def current_openid_request
    @current_openid_request ||= HumbleOpenidRequest.find_by_token(session[:request_token]) if session[:request_token]
  end

  def render_404
    render_error(404)
  end

  def render_422
    render_error(422)
  end

  def render_500
    render_error(500)
  end

  def render_error(status_code)
    render :file => "#{Rails.root}/public/#{status_code}", :formats => [:html], :status => status_code, :layout => false
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :authentication_token, :remember_me) }
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :username, :email, :password, :authentication_token, :remember_me) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :authentication_token, :current_password) }
  end

  private

  def scheme
    $humble_config['use_ssl'] ? 'https' : 'http'
  end

  def email_as_login?
    $humble_config['email_as_login']
  end
end
